package com.aididi.controller;

import com.aididi.config.OSSProperties;
import com.aididi.config.OssConfig;
import com.aididi.util.R;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ：xuzexiang
 * @description：aliyun OSS文件上传
 * @date ： 2021/11/4 11:23
 */
@RestController
public class OSSController {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private OSS ossClient;


    /**
     * 返回上传 Policy和签名
     * @return
     */
    @RequestMapping("/oss/policy")
    public R policy () {
        Map<String, String> respMap = new LinkedHashMap<String, String>();

        String host = "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 用户上传文件时指定的前缀 : 2020-12-12/
        String dir = simpleDateFormat.format(new Date()) + "/";

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            PolicyConditions policyConds = new PolicyConditions();
            // PostObject请求最大可支持的文件大小为 5GB，即 CONTENT_LENGTH_RANGE为 5*1024*1024*1024
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            // 发请求 PostPolicy
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap.put("accessid", ossProperties.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return R.success(respMap);
    }
}
